<?php

use app\common\model\Table;
use Workerman\Worker;
use \Workerman\Lib\Timer;
use \app\home\service\CardSettlementService;

require_once __DIR__ . '/../../../vendor/autoload.php';

// 心跳关闭连接
define('HEARTBEAT_TIME', 600);

// 初始化一个worker容器，监听1234端口
//,$context
$worker = new Worker('websocket://0.0.0.0:2000');

// ====这里进程数必须必须必须设置为1====
$worker->count = 1;
// 新增加一个属性，用来保存uid到connection的映射(uid是用户id或者客户端唯一标识)
$worker->uidConnections = array();
// 当有客户端发来消息时执行的回调函数
$worker->onMessage = function ($connection, $data) {
    global $worker;
    static $request_count;
    // 业务处理略
    if (++$request_count > 10000) {
        // 请求数达到10000后退出当前进程，主进程会自动重启一个新的进程
        Worker::stopAll();
    }

    // 判断当前客户端是否已经验证,即是否设置了uid
    if (!isset($connection->uid)) {
        $connection->lastMessageTime = time();
        $data = json_decode($data, true);
        //绑定uid
        $connection->uid = $data['user_id'];
        if (!isset($data['user_id']) || !isset($data['table_id']) || !isset($data['game_type'])) {
            return $connection->send('连接成功，参数错误');
        }

        $connection->data_info = $data;
        $worker->uidConnections[$connection->uid] = $connection;
        return $connection->send('连接成功');
    }
};

// 添加定时任务 每秒发送
$worker->onWorkerStart = function ($worker) {
    Timer::add(1, function () use ($worker) {
        foreach ($worker->connections as $key => &$connection) {
            $data = isset($connection->data_info) ? $connection->data_info : '';
            //没有用户数据 直接退出
            // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
            if (empty($data)) {
                continue;
            }
            // 信息进行处理
            //获取台桌信息
            if (isset($data['user_type']) && $data['user_type'] == 'table_info'){
                //每个游戏的台桌列表。不存在就是所有台桌
                $map = [];
                if ($data['game_type'] > 0) $map['game_type'] = $data['game_type'];
                $list = Table::cache()->page_repeat($map,'list_order asc');
                $list = $list->hidden(['game_play_staus', 'is_dianji', 'is_weitou', 'is_diantou', 'list_order',]);
                //计算台桌倒计时
                if (empty($list)) {
                    $connection->send('没有台桌信息');
                    continue;
                }

                foreach ($list as &$value) {
                    //获取视频地址
                    $value = Table::table_opening_count_down($value);
                    $value->p = rand(10, 40) . '.' . rand(1, 9) . 'k/' . rand(10, 40);
                    $value->t = rand(10, 40) . '.' . rand(1, 9) . 'k/' . rand(10, 40);
                    $value->b = rand(10, 40) . '.' . rand(1, 9) . 'k/' . rand(10, 40);
                }

                $connection->send(json_encode(['code'=>200,'data'=>$list]));
                continue;
            }
            else{
                //获取台桌开牌信息
                $newOpen = new CardSettlementService();
                $pai_result = $newOpen->get_pai_info($data['table_id'], $data['game_type']);
//                $connection->send('$data:'.json_encode($data));
//                $connection->send('$newOpen:'.json_encode($newOpen));
//                $connection->send('$pai_result:'.json_encode($pai_result));
                //没有扑克信息直接退出
                if (empty($pai_result)) {
                    $connection->data_info = $data;
                    $connection->send('没有扑克信息');
                    continue;
                }
                $connection->send(json_encode(['code' => 200, 'msg' => '成功', 'data' => $pai_result, 'bureau_number' => bureau_number($data['table_id'])]));
                continue;
            }
        }
    });
};


// 当有客户端连接断开时
$worker->onClose = function ($connection) {
    global $worker;
    if (isset($connection->uid)) {
        $connection->close();
        // 连接断开时删除映射
        unset($worker->uidConnections[$connection->uid]);
        echo "断开连接";
    }
};

// 向所有验证的用户推送数据
function broadcast($message)
{
    global $worker;
    foreach ($worker->uidConnections as $connection) {
        $connection->send($message);
    }
}

// 针对uid推送数据
function sendMessageByUid($uid, $message)
{
    global $worker;
    if (isset($worker->uidConnections[$uid])) {
        $connection = $worker->uidConnections[$uid];
        $connection->send($message);
    }
}

// 运行所有的worker（其实当前只定义了一个）
Worker::runAll();